var express = require('express');
var router = express.Router();
var md5 = require('md5-node')
var {query} = require('../../utils/db')
// 显示登录页面
router.get('/login',(req,res)=>{
    res.render('admin/user/login')
})

// 用户登录操作
router.post('/login',(req,res)=>{
    //1, 检查应户名密码是否正确
    //2, 如果正确，将除密码外的用户信息，存入session
    //3, 跳转到后台首页
    var username = req.body.username
    var password = md5(req.body.password)
    var sql = `select * from users where username='${username}' and password='${password}' and flag=1`
    console.log(sql)
    query(sql,(data)=>{
        if(data){
            user = data[0]
            delete user.password
            //把用户信息存入session
            req.session.user = user
            req.flash('success',`欢迎${user.username}回来!`)
            res.redirect('/admin/category/list')
        }
    })
})

// 退出登录
router.get('/logout',(req,res)=>{
    req.session.user = null
    req.flash('success','注销成功')
    res.redirect('/admin/user/login')
})


// 显示注册页面
router.get('/reg',(req,res)=>{
    res.render('admin/user/reg')
})

// 用户注册
router.post('/reg',(req,res)=>{
    var username = req.body.username
    var password = req.body.password
    var password_md5 = md5(password)
    var sql = `insert into users (username,password,flag) values('${username}','${password_md5}',1)`
    console.log(sql)
    query(sql,(data)=>{
        req.flash('success','注册成功')
        res.redirect('/admin/user/login')
    })
})  

module.exports = router;